import requests
import csv

page_num = 30
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
    "Referer": "https://www.bilibili.com/",  # 关键头
}

cookies = {
    "smidV2": "20250222123408801da2ae8e2f8c53ce10af9e2cacb55000fcd1d2552df9cb0",
    "intercom-session-guh50jw4": "NXJHc0ZVbjlMWlRwUkk1N0dFS3pQTjNySytxQjU0cFN1Zk1QM013enVnL3NpTVRmRDNGOHBFK0VyckZzNWhveHpvUWxMd1ExTGZiUE9KWnVIRXhyZ0ppMk9RWFVZYTRBaWdTSEhJb0l6TE09LS1KS0cyVlNTQVBaRWoyWTg3TEdsVTJ3PT0=--c29e5766d26b5697f240e416a8ecbbc2975bed49",
    "HWWAFSESTIME": "1743742419397",
    "HWWAFSESID": "f1e56a8172360f35040",
    ".thumbcache_6b2e5483f9d858d7c661c5e276b6a6ae": "acA/fX1AyOasewq1u69MpfYSuv7DxFu15Iu/rmsV8IyXRqGVMo3MOxYQlPVTMZPS/TgqxGmuqHjgmUMWVm+b5w%3D%3D",
    "intercom-device-id-guh50jw4": "64b99244-7d4c-49f3-9fd8-b65da81c89be",
    "ds_session_id": "687bda2262b34080bd8c00dc90dba10a"
}
# 提前打开文件，写入表头
with open('b站.csv', 'a+', encoding='utf-8-sig', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(["标题", "类型", "描述", "链接"])  # 写入列名

    for i in range(1, 11):
        url = f"https://api.bilibili.com/x/web-interface/wbi/search/type?category_id=&search_type=video&ad_resource=5654&__refresh__=true&_extra=&context=&page={i}&page_size={page_num}&pubtime_begin_s=0&pubtime_end_s=0&from_source=&from_spmid=333.337&platform=pc&highlight=1&single_column=0&keyword=pythonxlwings&qv_id=2cS2hJM8UIBmiV99dRe8DCnpvFqRcCFi&source_tag=3&gaia_vtoken=&dynamic_offset=30&page_exp=0&web_location=1430654&w_rid=26eb3e628218e55b0f6c453f54f2c3e1&wts=1743753838"
        
        try:
            res = requests.get(url, headers=headers, cookies=cookies, timeout=10)
            print(f"第 {i} 页状态码:", res.status_code)  # 打印状态码
            
            if res.status_code != 200:
                print(f"⚠️ 请求失败，状态码: {res.status_code}")
                continue  # 跳过当前页
            data = res.json()
            jsonres = data.get('data', {}).get('result', [])
            
            for r in jsonres:
                title = r.get('title', '无标题')
                typename = r.get('typename', '无类型')
                description = r.get('description', '无描述')
                arcurl = r.get('arcurl', '无链接')
                writer.writerow([title, typename, description, arcurl])
                    
        except requests.exceptions.RequestException as e:
            print(f"第 {i} 页请求异常:", e)
        except Exception as e:
            print(f"第 {i} 页解析异常:", e)